package cn.edu.fzu.homemaking.common;

import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

/**
 * 常量池
 */
public final class ConstantPool {

    private ConstantPool() {
    }

    private static final LoadingCache<String, String>   STRING_CACHE  = CacheBuilder.newBuilder().initialCapacity(46000)
            .expireAfterAccess(24, TimeUnit.HOURS).build(
                    //
                    new CacheLoader<String, String>() {
                        @Override
                        public String load(String key) {
                            return key;
                        }
                    });

    private static final LoadingCache<Long, Long>       LONG_CACHE    = CacheBuilder.newBuilder().initialCapacity(2048)
            .expireAfterAccess(24, TimeUnit.HOURS).build(
                    //
                    new CacheLoader<Long, Long>() {
                        @Override
                        public Long load(Long key) {
                            return key;
                        }
                    });

    private static final LoadingCache<Integer, Integer> INTEGER_CACHE = CacheBuilder.newBuilder().initialCapacity(35000)
            .expireAfterAccess(24, TimeUnit.HOURS).build(
                    //
                    new CacheLoader<Integer, Integer>() {
                        @Override
                        public Integer load(Integer key) {
                            return key;
                        }
                    });


    public static final Integer cint(Integer key) {
        return key == null ? null : INTEGER_CACHE.getUnchecked(key);
    }


    public static final Long clong(Long key) {
        return key == null ? null : LONG_CACHE.getUnchecked(key);
    }


    public static final String cstr(String key) {
        return key == null ? null : STRING_CACHE.getUnchecked(key);
    }


    public static final String information() {
        StringBuilder sb = new StringBuilder();
        sb.append("string: ").append(STRING_CACHE.size()).append(',');
        sb.append("int: ").append(INTEGER_CACHE.size()).append(',');
        sb.append("long: ").append(LONG_CACHE.size());
        return sb.toString();
    }
}
